import {
  _decorator,
  Component,
  Node,
  Prefab,
  instantiate,
  find,
  Sprite,
  ProgressBar,
} from 'cc'
import { ResMgr } from '../Managers/ResMgr'
import { UIMgr } from '../Managers/UIMgr'

export class Game extends Component {
  
  public static Instance: Game = null

  onLoad() {
    if (Game.Instance === null) {
      console.log('[Game] Instance')
      Game.Instance = this
    } else {
      console.log('[Game] Instance Destroy')
      this.destroy()
      return
    }
  }

  public GameStart() {
    // 预加载
    let pkg = {
      GUI: {
        assetType: Prefab,
        urls: [
          'UIPrefabs/Loading',
          'UIPrefabs/UIGame',
          'UIPrefabs/ShowRoom'
        ],
      },
    }
    ResMgr.Instance.preloadResPackage(
      pkg,
      (now: number, total: number) => {
        // 加载进度
        let per = now / total
        console.log(`[Game] loading : ${now}/${total}`)
        this.setProgress(per)
      },
      () => {
        // 加载菜单
        console.log('[Game] loading OK')
        setTimeout(() => {
          this.EnterGameScene()
        }, 1000)
      }
    )
  }

  public EnterGameScene() {
    // 释放资源
    // let uiGamePrefab = ResMgr.Instance.getAsset("GUI", "UIPrefabs/UIGame")
    // let uiGame = instantiate(uiGamePrefab)
    // this.node.addChild(uiGame)

    // UIMgr.Instance.removeUI('Loading')
    UIMgr.Instance.showUI('UIGame')
  }

  setProgress(val: number) {
    this.node.getComponentInChildren(ProgressBar).progress = val
  }

}
